// -----------------------------------------------------------------------
//  <copyright file="TableNamePrefixConfiguration.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024-04-10 1:38</last-date>
// -----------------------------------------------------------------------

using OSharp.Extensions;
using OSharp.Reflection;


namespace DaprPlus.EntityFrameworkCore;

/// <summary>
/// 表名前缀配置
/// </summary>
public class TableNamePrefixConfiguration : IEntityBatchConfiguration
{
    /// <summary>
    /// 配置指定的<see cref="IMutableEntityType"/>
    /// </summary>
    /// <param name="modelBuilder">模型构建器</param>
    /// <param name="mutableEntityType">实体的<see cref="IMutableEntityType"/>类型</param>
    public void Configure(ModelBuilder modelBuilder, IMutableEntityType mutableEntityType)
    {
        var prefix = GetTableNamePrefix(mutableEntityType.ClrType);
        if (prefix.IsNullOrEmpty())
        {
            return;
        }

        var tableName = $"{prefix}_{mutableEntityType.GetTableName()}";
        modelBuilder.Entity(mutableEntityType.ClrType).ToTable(tableName);
    }

    /// <summary>
    /// 从实体类型获取表名前缀
    /// </summary>
    /// <param name="entityType">实体类型</param>
    /// <returns></returns>
    protected virtual string? GetTableNamePrefix(Type entityType)
    {
        TableNamePrefixAttribute attribute = entityType.GetAttribute<TableNamePrefixAttribute>();
        return attribute?.Prefix;
    }
}
